//
//  AYSUserViewController.m
//  AiYingShiProject
//
//  Created by lanou on 15/10/27.
//  Copyright (c) 2015年 李晓理. All rights reserved.
//

#import "AYSUserViewController.h"
#import "AYSRequestManager.h"
#import "PictureModel.h"
#import "PictureTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "UIView_extra.h"
#import "UIView+WLFrame.h"
#import "AppDelegate.h"
#import "PicDetailViewController.h"
#import "MJRefresh.h"
#import "UIScrollView+MJRefresh.h"
#import "SVProgressHUD.h"
#import "AppDelegate.h"
#import "AYSSideViewController.h"
@interface AYSUserViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UISegmentedControl *segmentControl;
@property (nonatomic, strong) NSMutableArray *classicPicDataArray;
@property (nonatomic, strong) NSMutableArray *recommentPicDataArray;
@property (nonatomic, strong) NSMutableArray *wonderfulPicDataArray;
@property (nonatomic, strong) NSMutableArray *picNameArray;
@end
@implementation AYSUserViewController
#pragma wark ===========懒加载
- (NSMutableArray *)classicPicDataArray
{
    if (!_classicPicDataArray)
    {
        _classicPicDataArray = [[NSMutableArray alloc] init];
    }
    return _classicPicDataArray;
}

- (NSMutableArray *)recommentPicDataArray
{
    if (!_recommentPicDataArray)
    {
        _recommentPicDataArray = [[NSMutableArray alloc] init];
    }
    return _recommentPicDataArray;
}

- (NSMutableArray *)wonderfulPicDataArray
{
    if (!_wonderfulPicDataArray)
    {
        _wonderfulPicDataArray = [[NSMutableArray alloc] init];
    }
    return _wonderfulPicDataArray;
}

- (NSMutableArray *)picNameArray
{
    if (!_picNameArray)
    {
        _picNameArray = [[NSMutableArray alloc] init];
    }
    return _picNameArray;
}
#pragma wark =========================数据请求
//去除重复图片的方法
- (BOOL)isHaveSamePicModel:(PictureModel *)model
{
    if (self.picNameArray.count == 0) {     //还没有数据，新增
        [self.picNameArray addObject:model.title];
        return NO;
    }else{
        BOOL isHaveSame = NO;
        //遍历，看是否有重复
        for (NSString *aTitle in self.picNameArray) {
            if ([aTitle isEqualToString:model.title]) {
                isHaveSame = YES;
            }
        }
        //有重复，返回Yes，否则，新增
        if (isHaveSame) {
            return YES;
        }else{
            [self.picNameArray addObject:model.title];
            return NO;
        }
    }
    return NO;
}

- (void)requestDataWithClassPictureWithUrl:(NSString *)url
{
    [AYSRequestManager requestWithType:GET url:url parDic:nil finish:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSArray *resultArr = dic[@"rows"];
        
        for (NSDictionary *dict in resultArr)
        {
            PictureModel *model = [PictureModel pictureModelWithDictionary:dict];
            model.collectionType = [NSString stringWithFormat:@"%zi",self.segmentControl.selectedSegmentIndex];
            
            if (![self isHaveSamePicModel:model])
            {
                [self.classicPicDataArray addObject:model];
            }
        }
      [self.tableView reloadData];
        
    } error:^(NSError *error)
     {
         NSLog(@"经典网络请求失败");
     }];
    
}

- (void)requestDataWithRecommentPictureWithUrl:(NSString *)url
{
    [AYSRequestManager requestWithType:GET url:url parDic:nil finish:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        NSArray *resultArr = dic[@"rows"];
        for (NSDictionary *dict in resultArr)
        {
        PictureModel *model = [PictureModel pictureModelWithDictionary:dict];
        model.collectionType = [NSString stringWithFormat:@"%zi",self.segmentControl.selectedSegmentIndex];
        //有一个nativeAD反复出现,舍弃
          if (![model.ID isEqualToString:@"native_ad"])
          {
            
            if (![self isHaveSamePicModel:model])
            {
                [self.recommentPicDataArray addObject:model];
            }
            
           }
        
       }
        
      [self.tableView reloadData];
     
    } error:^(NSError *error)
     {
         NSLog(@"推荐网络请求失败");
     }];
    
}

- (void)requestDataWithWonderfulPictureWithUrl:(NSString *)url
{
    [AYSRequestManager requestWithType:GET url:url parDic:nil finish:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        NSArray *resultArr = dic[@"items"];
        for (NSDictionary *dict in resultArr)
        {
        PictureModel *model = [PictureModel pictureModelWithDictionary:dict];
        model.collectionType = [NSString stringWithFormat:@"%zi",self.segmentControl.selectedSegmentIndex];
        
        if (![self isHaveSamePicModel:model]) {
            [self.wonderfulPicDataArray addObject:model];
        }
     }
    [self.tableView reloadData];
     } error:^(NSError *error)
     {
         NSLog(@"精彩网络请求失败");
     }];
    
}

//更多 经典
- (void)reloadMoreClassicPicData
{
    
    PictureModel *model = [self.classicPicDataArray lastObject];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kClassicFunnyPicForMoreURL,model.cTime];
    
    [AYSRequestManager requestWithType:GET url:urlStr parDic:nil finish:^(NSData *data) {
        
        NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        for (NSDictionary *dic in arr)
        {
            PictureModel *model = [PictureModel pictureModelWithDictionary:dic];
            model.collectionType = [NSString stringWithFormat:@"%zi",self.segmentControl.selectedSegmentIndex];
            //去重
            if (![self isHaveSamePicModel:model]) {
                [self.classicPicDataArray addObject:model];
            }
            
        }
        [self.tableView reloadData];
     } error:^(NSError *error)
     {
         NSLog(@"精彩网络请求失败");
     }];

    
    
}

//更多 推荐
- (void)reloadMoreRecommentData
{
    PictureModel *model = [self.recommentPicDataArray lastObject];
    NSString *urlStr = [kRecommentPicForMoreURL stringByAppendingString:model.cTime];
    
    [AYSRequestManager requestWithType:GET url:urlStr parDic:nil finish:^(NSData *data) {
        
        NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        for (NSDictionary *dic in arr)
        {
            PictureModel *model = [PictureModel pictureModelWithDictionary:dic];
            model.collectionType = [NSString stringWithFormat:@"%ld",(long)self.segmentControl.selectedSegmentIndex];
            //有一个nativeAD反复出现,舍弃
            if (![model.ID isEqualToString:@"native_ad"]) {
                
                //去重
                if (![self isHaveSamePicModel:model]) {
                    [self.recommentPicDataArray addObject:model];
                }
                
        }
         }
        [self.tableView reloadData];
        
    } error:^(NSError *error)
     {
         NSLog(@"精彩网络请求失败");
     }];

}

//更多 精彩
- (void)reloadMoreWonderfulData
{
    PictureModel *model = [self.wonderfulPicDataArray lastObject];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@%@",kWonderfulPicForMorePartOneURL,model.cTime,kWonderfulPicForMorePartTwoURL];
    
    [AYSRequestManager requestWithType:GET url:urlStr parDic:nil finish:^(NSData *data) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        for (NSDictionary *dic in dict[@"items"])
        {
            PictureModel *model = [PictureModel pictureModelWithDictionary:dic];
            model.collectionType = [NSString stringWithFormat:@"%ld",(long)self.segmentControl.selectedSegmentIndex];
            
            //去重
            if (![self isHaveSamePicModel:model]) {
                
                [self.wonderfulPicDataArray addObject:model];
            }
            
        }
        [self.tableView reloadData];
        
        
    } error:^(NSError *error)
     {
         NSLog(@"精彩网络请求失败");
     }];
    
}

- (void)clickLeftButton
{
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    AYSSideViewController *sideViewController = [delegate sideViewController];
    [sideViewController showLeftViewController:true];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
     self.view.backgroundColor = [UIColor blackColor];
    UIColor *color = [UIColor whiteColor];
    NSDictionary *dict = [NSDictionary dictionaryWithObject:color forKey:UITextAttributeTextColor];
    self.navigationController.navigationBar.titleTextAttributes = dict;
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"抽屉菜单"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] style:(UIBarButtonItemStylePlain) target:self action:@selector(clickLeftButton)];
    self.navigationItem.leftBarButtonItem = leftButton;
    [self requestDataWithClassPictureWithUrl:kClassicFunnyPicForBeginURL];
    [self setSegmentControl];
    [self setTableView];
    
#pragma  wark =====================上拉刷新
    __weak UITableView *tableView = self.tableView;
    tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
            switch (self.segmentControl.selectedSegmentIndex)
            {
                case 0:
                {
                    [self reloadMoreClassicPicData];
                    
                }
                    break;
                case 1:
                {
                    [self reloadMoreRecommentData];
                }
                    break;
                case 2:
                {
                    [self reloadMoreWonderfulData];
                }
                    break;
                    
                default:
                    break;
            }
            [tableView reloadData];
            [tableView.footer endRefreshing];
        
    }];

#pragma wark ===================下拉刷新
    // 下拉刷新
    tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
    switch (self.segmentControl.selectedSegmentIndex)
    {
            case 0:
               {
                   [self refreshDataWithUrl:kClassicFunnyPicForBeginURL arrar:_classicPicDataArray];
               }
                break;
            case 1:
            {
                [self refreshDataWithUrl:kRecommentPicForBeginURL arrar:_recommentPicDataArray];
            }
                break;
            case 2:
            {
                [self refreshDataWithUrl:kWonderfulPicForBeginRUL arrar:_wonderfulPicDataArray];
            }
                break;
                
            default:
                break;
        }
        [self.tableView reloadData];
        // 结束刷新
        [tableView.header endRefreshing];
       
    }];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    tableView.header.automaticallyChangeAlpha = YES;
    
}

- (void)refreshDataWithUrl:(NSString *)url arrar:(NSMutableArray *)array
{
    if (array.count > 0)
    {
        [AYSRequestManager requestWithType:GET url:url parDic:nil finish:^(NSData *data) {

            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSArray *resultArr;
            if (self.segmentControl.selectedSegmentIndex == 2)
            {
                resultArr = [NSMutableArray arrayWithArray:dic[@"items"]];
            }
            else
            {
                resultArr = [NSMutableArray arrayWithArray:dic[@"rows"]];
            }
            // 比较时间戳 如果新来的数据的最后一个时间戳比原有的数据的第一个时间戳大 就重新加载数据
            PictureModel *newModel = [PictureModel pictureModelWithDictionary:[resultArr lastObject]];
            PictureModel *oldModel = [array firstObject];
            if ([newModel.cTime floatValue] > [oldModel.cTime floatValue])
            {
                [array removeAllObjects];
                
                for (NSDictionary *dic in resultArr)
                {
                        PictureModel *model = [PictureModel pictureModelWithDictionary:dic];
                        model.collectionType = [NSString stringWithFormat:@"%zi",self.segmentControl.selectedSegmentIndex];
                    
                    //去重
                    if (![self isHaveSamePicModel:model]) {
                        
                        [_wonderfulPicDataArray addObject:model];
                    }
                }
                
            }else
            {
                for (int i = (int)(resultArr.count - 1); i >= 0; i--)
                {
                    NSDictionary *dic = resultArr[i];
                    PictureModel *newModel = [PictureModel pictureModelWithDictionary:dic];
                    newModel.collectionType = [NSString stringWithFormat:@"%zi", self.segmentControl.selectedSegmentIndex];
                    float maxTime = 0.0;
                    // 遍历得到最大的时间戳
                    for (PictureModel *model in array)
                    {
                        maxTime = [model.cTime floatValue] > maxTime ? [model.cTime floatValue] : maxTime;
                    }
                    //新的数据时间戳比数组里的都大,插入数据 到最前面
                    if ([newModel.cTime floatValue] > maxTime && !([newModel.ID isEqualToString:@"native_ad"]))
                    {
                        
                        //去重
                        if (![self isHaveSamePicModel:newModel]) {
                            
                            [array insertObject:newModel atIndex:0];
                        }
                    }
                }
            }
        } error:^(NSError *error)
         {
             NSLog(@"经典网络请求失败");
         }];

    }

}



#pragma mark ================= 页面设置
- (void)setSegmentControl
{
    self.segmentControl = [[UISegmentedControl alloc] initWithItems:@[@"经典",@"推荐",@"精彩"]];
    self.segmentControl.frame = CGRectMake(0, 0, 180, 30);
    self.segmentControl.selectedSegmentIndex = 0;
    [self.segmentControl addTarget:self action:@selector(segmentControlAction:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = self.segmentControl;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}

- (void)setTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 50)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[PictureTableViewCell class] forCellReuseIdentifier:@"Cell"];
    self.tableView.backgroundColor = [UIColor blackColor];
    
    [self.view addSubview:self.tableView];
    
    
}

#pragma mark ============== 点击Segment进行数据请求
- (void)segmentControlAction:(UISegmentedControl *)segment
{
    [SVProgressHUD show];
    switch (segment.selectedSegmentIndex)
    {
        case 0:
        {
            [self requestDataWithClassPictureWithUrl:kClassicFunnyPicForBeginURL];
        }
            break;
        case 1:
        {
            [self requestDataWithRecommentPictureWithUrl:kRecommentPicForBeginURL];
        }
            break;
            
        case 2:
        {
            [self requestDataWithWonderfulPictureWithUrl:kWonderfulPicForBeginRUL];
        }
            break;
        default:
            break;
    }
    [SVProgressHUD dismiss];
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self segmentControlAction:self.segmentControl];
    [super viewWillAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [super viewWillDisappear:animated];
}


#pragma mark ===============tableView的相关设置
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (self.segmentControl.selectedSegmentIndex)
    {
        case 0:
        {
            return self.classicPicDataArray.count;
        }
             break;
        case 1:
        {
            return self.recommentPicDataArray.count;
        }
            break;
        case 2:
        {
            return self.wonderfulPicDataArray.count;
        }
            break;
            
        default: return 30;
            break;
    }
}

#pragma mark ===============计算行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (self.segmentControl.selectedSegmentIndex) {
        case 0:
        {
            PictureModel *model = self.classicPicDataArray[indexPath.row];
            return [self cellHeightForTitle:model.title WidthStr:model.pic_w HeightStr:model.pic_h];
        }
            break;
            
        case 1:
        {
            PictureModel *model = self.recommentPicDataArray[indexPath.row];
            return [self cellHeightForTitle:model.title WidthStr:model.pic_w HeightStr:model.pic_h];
        }
            break;
            
        case 2:
        {
            PictureModel *model = self.wonderfulPicDataArray[indexPath.row];
            return [self cellHeightForTitle:model.title WidthStr:model.pic_w HeightStr:model.pic_h];
            
        }
            break;
            
        default: return 50;
            break;
    }
}

- (CGFloat)cellHeightForTitle:(NSString *)title WidthStr:(NSString *)widthStr HeightStr:(NSString *)heightStr
{
    float heightOfPic = [heightStr floatValue] * kLengthOfMainPicture / [widthStr floatValue];
    float heightOftitle = [self getHeightWithString:title Width:kLengthOfTitle Font:kFontOfTitle];
    if (heightOftitle < 35)
    {
        heightOftitle = 35;
    }
    return heightOftitle + heightOfPic + kHeightOfCollectButton + kHeightOfTimeLabel + 30;
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (self.segmentControl.selectedSegmentIndex)
    {
        case 0:
        {
            PictureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
            PictureModel *model = self.classicPicDataArray[indexPath.row];
            return [self setUpPictureTableViewCell:cell PicModel:model IndexPath:indexPath];
        }
            break;
        case 1:
        {
            PictureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
            PictureModel *model = self.recommentPicDataArray[indexPath.row];
            return [self setUpPictureTableViewCell:cell PicModel:model IndexPath:indexPath];
        }
            break;
        case 2:
        {
            PictureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
            PictureModel *model = self.wonderfulPicDataArray[indexPath.row];
            return [self setUpPictureTableViewCell:cell PicModel:model IndexPath:indexPath];
        }
            break;
        default: return nil;
            break;
    }
}

- (PictureTableViewCell *)setUpPictureTableViewCell:(PictureTableViewCell *)cell PicModel:(PictureModel *)model IndexPath:(NSIndexPath *)indexPath
{
    cell.timeLabel.text = model.timeStr;
    cell.titleLabel.text = model.title;
    [cell.mainImageView sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:[UIImage imageNamed:@"loadingPic00"]];
    
    
    //自适应 题目高度
    cell.titleLabel.height = [self getHeightWithString:model.title Width:kLengthOfTitle Font:cell.titleLabel.font];
    if (cell.titleLabel.height < 35) {
        cell.titleLabel.height = 35;
    }
    
    
    // 图片高度 根据给定的比例设置
    cell.mainImageView.top = cell.titleLabel.top + cell.titleLabel.height;
    float heightOfPic = [model.pic_h floatValue] * kLengthOfMainPicture / [model.pic_w floatValue];
    cell.mainImageView.height = heightOfPic;
    //背景 高度
    cell.backView.height = cell.titleLabel.height + cell.mainImageView.height + kHeightOfCollectButton + kHeightOfTimeLabel + 10;
    cell.bottomView.top = cell.mainImageView.bottom;
    return cell;
}



- (CGFloat)getHeightWithString:(NSString *)str Width:(CGFloat)width Font:(UIFont *)font
{
    CGRect rect = [str boundingRectWithSize:CGSizeMake(width, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName] context:nil];
    return rect.size.height;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PictureModel *model = nil;
    
    switch (self.segmentControl.selectedSegmentIndex)
    {
        case 0:
        {
            model = self.classicPicDataArray[indexPath.row];
        }
            break;
            
        case 1:
        {
            model = self.recommentPicDataArray[indexPath.row];
        }
            break;
            
        case 2:
        {
            model = self.wonderfulPicDataArray[indexPath.row];
        }
            break;
            
        default:
            break;
    }
    
    [self showDetailPicWithPicModel:model indexPath:indexPath];
    
}

- (void)showDetailPicWithPicModel:(PictureModel *)model indexPath:(NSIndexPath *)indexPath
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    PicDetailViewController *detailVC = [[PicDetailViewController alloc] init];
    detailVC.picHeight = [model.pic_h floatValue];
    detailVC.picWidth = [model.pic_w floatValue];
    detailVC.picURLStr = model.pic;
    [delegate.window.rootViewController presentViewController:detailVC animated:YES completion:nil];
//    [self.navigationController pushViewController:detailVC animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
